<template>
  <div :class="['input-wrap', border && 'input-wrap-border']">
    <input class="input-wrap-input" :type="type" ref="input" :style="{fontSize: fontSize + 'px', height: height + 'px', lineHeight: height + 'px', padding: padding + 'px',
      textAlign: textAlign}"
           :placeholder="placeholder" :value="val" :maxlength="maxLength"
           @change="inputChange"
           v-on:input="updateValue"/>
    <text class="icon clear-btn"
          :style="{width: height, height: height, lineHeight: height, opacity: val ? 1 : 0}"
          @click="clear">&#xe61b;</text>
  </div>
</template>
<style lang="scss">
  @import "../sass/var";
  @import "../sass/mixin";
  @import "../sass/icon";
  .input-wrap {
    flex-direction: row;
    position: relative;
    align-items: center;
    &-border {
      @include border(1, solid, #ddd)
    }
    &-input {
      flex: 1;
      color: $color;
      placeholder-color: #999;
    }
  }
  .clear-btn {
    font-size: 24px;
    text-align: center;
    color: $color-muted;
    &-light {
      color: #ffffff;
    }
  }

</style>
<script>
require('../include/page-xdom')
let platform = require('../include/platform')
module.exports = {
  mixins: [

  ],
  props: {
    placeholder: {default: ''},
    border: {default: 0},
    value: {default: ''},
    fontSize: {default: 32},
    height: {default: 52},
    type: {default: 'text'},
    maxLength: {default: Number.MAX_SAFE_INTEGER},
    padding: {default: 0},
    textAlign: {default: 'left'}
  },

  data () {
    return {
      val: ''
    }
  },
  components: {},
  created () {
    this.val = this.value
    this.$watch('value', (newVal, oldVal) => {
      this.val = newVal
      if (platform.isAndroid()) {
        this.$el('input').event.input('')
      }
    })
  },
  methods: {
    updateValue (e) {
      // 通过 input 事件带出数值
      this.$emit('update:value', this.getVal(e))
    },
    inputChange (e) {
      this.val = this.getVal(e)
      this.$emit('change', this.getVal(e))
    },
    getVal (e) {
      if (platform.isWeb()) {
        return e.target.value
      } else {
        return e.target.attr.value
      }
    },
    clear () {
      this.val = ''
      if (platform.isAndroid()) {
        this.$el('input').event.input('')
      }
      // 通过 input 事件带出数值
      this.$emit('update:value', '')
      this.$refs['input'].focus()
    }
  }
}
</script>
